<?php

/**
 * 功能: 去掉字符串中的反斜线
 * 参数： 
 *         string/array $value 
 * 返回值:
 *         string/array       
 */
function stripslashes_deep($value) {
    $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
    return $value;
}

/**
 * 功能: 给特殊字符加上斜线
 * 参数： 
 *         string/array $value 
 * 返回值:
 *         string/array       
 */
function addslashes_deep($value) {
    $value = is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    return $value;
}

/**
 * 功能: 自动生成model文件
 * 作者: 齐圣福
 * 最后一次修改时间: 2011年5月3日10:03:14
 * 参数： 
 *     string $modelName     model名
 *     string $table         表名
 *     string $primaryKey    主键
 *     string $db            数据库名
 * 返回值:
 *     bool   true成功  flase失败
 *                    
 */
function createModelFile($modelName, $table, $primaryKey, $db) {
    if (empty($modelName)) {
	return false;
    }
    $handle = @fopen(APP_PATH . '/models/' . $modelName . '.class.php', 'w+');
    $content = '<?php' . "\r\n" . '
        class ' . $modelName . ' extends Model {' . "\r\n" . ' 
           public $db = \'' . $db . '\';' . "\r\n" . '
           public $table = \'' . $table . '\';' . "\r\n" . '
           public $primaryKey = \'' . $primaryKey . '\';' . "\r\n" . '
        }' . "\r\n" . '
    ' . "\r\n";
    if ($handle && @fwrite($handle, $content)) {
	@fclose($handle);
	return true;
    }
    return false;
}

/**
 * 加载文件
 * @param  string $classname 文件名
 * @return  
 */
function Loader($classname) {
    $fileArr = explode('::', $classname);
    $pathType = strtoupper($fileArr[0]);    //类库类型（系统还是项目类库）
    $classname = isset($fileArr[1]) ? ucwords($fileArr[1]) : ucwords($classname);
    //Loader('sys|app|mod::$classname') 方式加载
    if (count($fileArr) == 2) {
	if (in_array($pathType, array('APP', 'SYS'))) {
	    $path = $pathType == 'APP' ? APP_PATH : SYS_PATH;
	    $loadFile = $path . "/lib/{$classname}.class.php";
	} elseif ($pathType == 'MOD') {
	    $loadFile = APP_PATH . "/models/{$classname}Model.class.php";
	}
	//new $classnameModel（）形式直接加载  
    } else {
	$loadFile = APP_PATH . "/models/{$classname}.class.php";
    }

    if (file_exists($loadFile)) {
	require_once($loadFile);
    } else {
	if (SysConfig::$D_BUG) {
	    exit("ERROR {$classname}：File {$loadFile} is not exists");
	}
    }
    return '';
}

//获取IP
function getIp() { //获取IP
    if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
	$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else if (isset($_SERVER["HTTP_CLIENT_IP"]))
	$ip = $_SERVER["HTTP_CLIENT_IP"];
    else if ($_SERVER["REMOTE_ADDR"])
	$ip = $_SERVER["REMOTE_ADDR"];
    else if (getenv("HTTP_X_FORWARDED_FOR"))
	$ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("HTTP_CLIENT_IP"))
	$ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("REMOTE_ADDR"))
	$ip = getenv("REMOTE_ADDR");
    else
	$ip = "Unknown";
    return $ip;
}

/**
 * 调用异常的show方法
 *
 * @param	Exception	$e
 */
function handleException(Exception $e) {
	if ($e instanceof pay_ext_Exception) {
		$e->show ();
		exit ();
	}
	print $e;
}

/**
 * 得到PHP错误，并报告一个系统错误
 *
 * @param	integer		$errorNo
 * @param	string		$message
 * @param	string		$filename
 * @param	integer		$lineNo
 */
function handleError($errorNo, $message, $filename, $lineNo) {
	if (error_reporting () != 0) {
		$type = 'error';
		switch ($errorNo) {
			case 2 :
				$type = 'warning';
				break;
			case 8 :
				$type = 'notice';
				break;
		}
		throw new pay_ext_Exception ( 'PHP ' . $type . ' in file ' . $filename . ' (' . $lineNo . '): ' . $message, 0 );
	}
}

//循环建立目录齐圣福2011年3月17日8:19:30修改
function mkdirs($path, $mode = 0777) {
    $dirs = explode('/', $path);
    $count = count($dirs);
    $pos = strrpos($dirs[$count - 1], '.');
    if ($pos) {
	$count = $count - 1;
    }
    for ($c = 0; $c < $count; $c++) {
	$thispath = "";
	for ($cc = 0; $cc <= $c; $cc++) {
	    $thispath .= $dirs[$cc] . '/';
	}
	if (!file_exists($thispath)) {
	    @mkdir($thispath, $mode);
	}
    }
    return $pos ? file_exists(dirname($path)) : file_exists($path);
}

/**
 * 根据中文裁减字符串
 * @param string $string -  待截取的字符串
 * @param integer $length - 截取字符串的长度
 * @param string $charset - 编码
 * @param string $dot - 缩略后缀
 * @return string 返回带省略号被裁减好的字符串
 */
function cutStr($string, $length, $charset = 'utf-8', $dot = ' ...') {
    if (strlen($string) <= $length) {
	return $string;
    }
    $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
    $strcut = '';
    if (strtolower($charset) == 'utf-8') {

	$n = $tn = $noc = 0;
	while ($n < strlen($string)) {
	    $t = ord($string[$n]);
	    if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
		$tn = 1;
		$n++;
		$noc++;
	    } elseif (194 <= $t && $t <= 223) {
		$tn = 2;
		$n += 2;
		$noc += 2;
	    } elseif (224 <= $t && $t < 239) {
		$tn = 3;
		$n += 3;
		$noc += 2;
	    } elseif (240 <= $t && $t <= 247) {
		$tn = 4;
		$n += 4;
		$noc += 2;
	    } elseif (248 <= $t && $t <= 251) {
		$tn = 5;
		$n += 5;
		$noc += 2;
	    } elseif ($t == 252 || $t == 253) {
		$tn = 6;
		$n += 6;
		$noc += 2;
	    } else {
		$n++;
	    }
	    if ($noc >= $length) {
		break;
	    }
	}
	if ($noc > $length) {
	    $n -= $tn;
	}
	$strcut = substr($string, 0, $n);
    } else {
	for ($i = 0; $i < $length; $i++) {
	    $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
	}
    }
    $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
    return $strcut . $dot;
}

/**
  +----------------------------------------------------------
 * 字符串截取，支持中文和其它编码
  +----------------------------------------------------------
 * @static
 * @access public
  +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
  +----------------------------------------------------------
 * @return string
  +----------------------------------------------------------
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
    if (function_exists("mb_substr"))
	$slice = mb_substr($str, $start, $length, $charset);
    elseif (function_exists('iconv_substr')) {
	$slice = iconv_substr($str, $start, $length, $charset);
    } else {
	$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$slice = join("", array_slice($match[0], $start, $length));
    }
    if ($suffix && $str != $slice)
	return $slice . "...";
    return $slice;
}

/**
 * 功能: 获取微妙级的时间戳
 * 作者: php手册
 * 最后一次修改时间: 2011年4月19日16:00:30
 * 参数： 
 *         
 * 返回值:
 *                
 */
function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}

/**
 * 功能: 判断某个字符串是否存在某个字符
 * 作者: php手册
 * 最后一次修改时间: 2011年4月19日16:00:30
 * @param string $haystack - 需要查找的字符串
 * @param string $needle - 查找目标
 * @return bool true 或者 false
 *                
 */
function strexists($haystack, $needle) {
    return !(strpos($haystack, $needle) === FALSE);
}

//判断是否是蜘蛛
function getrobot() {
    if (!defined('IS_ROBOT')) {
	$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
	$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
	if (!strexists($_SERVER['HTTP_USER_AGENT'], 'http://') && preg_match("/($kw_browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
	    define('IS_ROBOT', FALSE);
	} elseif (preg_match("/($kw_spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
	    define('IS_ROBOT', TRUE);
	} else {
	    define('IS_ROBOT', FALSE);
	}
    }
    return IS_ROBOT;
}

/**
 * 功能: 在所有加载的页面中搜索给定字符，主要用来阅读代码时查找变量来源和程序执行流程
 * 作者: 齐圣福
 * 最后一次修改时间:2011年6月2日22:10:03
 * 参数： 
 *     string $string   需要查找的变量
 *     bool   $exit     查找完成后程序中断还是继续执行  true:中断，false:继续运行    
 * 返回值:
 *                    
 */
function findStrFromIncludedFiles($string = '', $exit = true) {
    if (empty($string)) {
	return;
    }
    $included_files = get_included_files();
    foreach ($included_files as $filename) {
	echo $filename . '<BR>';
	$i = 1;
	$handle = fopen($filename, 'r');
	while (!feof($handle)) {
	    $buffer = fgets($handle, 4096);
	    if (strpos($buffer, $string) !== false) {
		$buffer = str_replace($string, '<font color = "blue">' . $string . '</font>', $buffer);
		echo $i . ' <font color = "green">' . $buffer . '</font><BR>';
	    }
	    $i++;
	}
	fclose($handle);
	echo '<HR>';
    }
    $exit && exit();
}

/**
 * 功能: 输出或返回一个变量的字符串表示，主要用于保存或者缓存变量到文件
 * 作者: 齐圣福
 * 最后一次修改时间: 2011年4月19日16:10:55
 * 参数： 
 *     string/array $var   需要查找的变量
 * 返回值:
 *                    
 */
function varToStr($var, $level = 0) {
    if (!is_array($var)) {
	return "'" . $var . "'";
    }
    return var_export($var, true);
}

/**
 * 功能: 刷新当前页面
 * 作者: 齐圣福
 * 最后一次修改时间: 2011年4月19日16:10:55
 * 参数： 
 *     string $method   刷新方式  默认php，否则js  
 * 返回值:
 *                    
 */
function redo($method = 'php') {
    $curPage = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
    if ($method == 'php') {
	header('location:' . $curPage);
	exit();
    }
    echo "<script  language='javascript'>window.location.href='" . $curPage . "';</script>";
    exit();
}

//解析UBB
function ubb($Text) {
    $Text = trim($Text);
    //$Text=htmlspecialchars($Text);
    $Text = preg_replace("/\\t/is", "  ", $Text);
    $Text = preg_replace("/\[h1\](.+?)\[\/h1\]/is", "<h1>\\1</h1>", $Text);
    $Text = preg_replace("/\[h2\](.+?)\[\/h2\]/is", "<h2>\\1</h2>", $Text);
    $Text = preg_replace("/\[h3\](.+?)\[\/h3\]/is", "<h3>\\1</h3>", $Text);
    $Text = preg_replace("/\[h4\](.+?)\[\/h4\]/is", "<h4>\\1</h4>", $Text);
    $Text = preg_replace("/\[h5\](.+?)\[\/h5\]/is", "<h5>\\1</h5>", $Text);
    $Text = preg_replace("/\[h6\](.+?)\[\/h6\]/is", "<h6>\\1</h6>", $Text);
    $Text = preg_replace("/\[separator\]/is", "", $Text);
    $Text = preg_replace("/\[center\](.+?)\[\/center\]/is", "<center>\\1</center>", $Text);
    $Text = preg_replace("/\[url=http:\/\/([^\[]*)\](.+?)\[\/url\]/is", "<a href=\"http://\\1\" target=_blank>\\2</a>", $Text);
    $Text = preg_replace("/\[url=([^\[]*)\](.+?)\[\/url\]/is", "<a href=\"http://\\1\" target=_blank>\\2</a>", $Text);
    $Text = preg_replace("/\[url\]http:\/\/([^\[]*)\[\/url\]/is", "<a href=\"http://\\1\" target=_blank>\\1</a>", $Text);
    $Text = preg_replace("/\[url\]([^\[]*)\[\/url\]/is", "<a href=\"\\1\" target=_blank>\\1</a>", $Text);
    $Text = preg_replace("/\[img\](.+?)\[\/img\]/is", "<img src=\\1>", $Text);
    $Text = preg_replace("/\[color=(.+?)\](.+?)\[\/color\]/is", "<font color=\\1>\\2</font>", $Text);
    $Text = preg_replace("/\[size=(.+?)\](.+?)\[\/size\]/is", "<font size=\\1>\\2</font>", $Text);
    $Text = preg_replace("/\[sup\](.+?)\[\/sup\]/is", "<sup>\\1</sup>", $Text);
    $Text = preg_replace("/\[sub\](.+?)\[\/sub\]/is", "<sub>\\1</sub>", $Text);
    $Text = preg_replace("/\[pre\](.+?)\[\/pre\]/is", "<pre>\\1</pre>", $Text);
    $Text = preg_replace("/\[email\](.+?)\[\/email\]/is", "<a href='mailto:\\1'>\\1</a>", $Text);
    $Text = preg_replace("/\[colorTxt\](.+?)\[\/colorTxt\]/eis", "color_txt('\\1')", $Text);
    $Text = preg_replace("/\[emot\](.+?)\[\/emot\]/eis", "emot('\\1')", $Text);
    $Text = preg_replace("/\[i\](.+?)\[\/i\]/is", "<i>\\1</i>", $Text);
    $Text = preg_replace("/\[u\](.+?)\[\/u\]/is", "<u>\\1</u>", $Text);
    $Text = preg_replace("/\[b\](.+?)\[\/b\]/is", "<b>\\1</b>", $Text);
    $Text = preg_replace("/\[quote\](.+?)\[\/quote\]/is", " <div class='quote'><h5>引用:</h5><blockquote>\\1</blockquote></div>", $Text);
    $Text = preg_replace("/\[code\](.+?)\[\/code\]/eis", "highlight_code('\\1')", $Text);
    $Text = preg_replace("/\[php\](.+?)\[\/php\]/eis", "highlight_code('\\1')", $Text);
    $Text = preg_replace("/\[sig\](.+?)\[\/sig\]/is", "<div class='sign'>\\1</div>", $Text);
    $Text = preg_replace("/\\n/is", "<br/>", $Text);
    return $Text;
}